import VueRouter from 'vue-router'

import LayoutUnauthorized from '@/layouts/LayoutUnauthorized.vue'
import LayoutAuthorized from '@/layouts/LayoutAuthorized.vue'
import LayoutAuthorizedFull from '@/layouts/LayoutAuthrizedFull.vue'

import { authorizedRoutes } from './authorized'
import { unauthorizedPaths, unauthorizedRoutes } from './unauthorized'
import { useAppStore } from '@/stores/app'
import { Toast } from 'vant'
import { authorizedFullRoutes } from './authorizedFull'
import { sendIsTabbarView } from '@/uni'
import { tabbarPaths } from './tabbar'

const router = new VueRouter({
  routes: [
    {
      path: '/unauthorized',
      component: LayoutUnauthorized,
      children: unauthorizedRoutes.filter(route => Boolean(route.path))
    },
    {
      path: '/',
      component: LayoutAuthorized,
      children: authorizedRoutes.filter(route => Boolean(route.path))
    },
    {
      path: '/',
      component: LayoutAuthorizedFull,
      children: authorizedFullRoutes.filter(route => Boolean(route.path))
    },
  ]
})

router.beforeEach((to, from, next) => {
  const appStore = useAppStore()

  appStore.title = to.meta?.title ?? 'IM'
  
  if (appStore.hasLogged) {
    if (to.name === 'Login') {
      sendIsTabbarView(true)
      return next({ name: 'Home' })
    }
  } else {
    if (to.name !== 'Login' && !unauthorizedPaths.includes(to.path)) {
      Toast.fail({ message: '您还未登录, 请先登录' })
      sendIsTabbarView(true)
      return next({ name: 'Login' })
    }
  }

  sendIsTabbarView(tabbarPaths.includes(to.path))
  next()
})

export default router
